package com.hotel.controller;

import com.hotel.factory.BeanFactory;
import com.hotel.service.*;
import com.hotel.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * servlet的公共类
 * Created by LinYaTing on 2018/11/25 21:31
 */
public abstract class BaseServlet extends HttpServlet {

    protected FoodService foodService = BeanFactory.getInstance("foodService", FoodService.class);
    protected FoodTypeService foodTypeService = BeanFactory.getInstance("foodTypeService", FoodTypeService.class);
    protected OrderDetailService orderDetailService = BeanFactory.getInstance("orderDetailService", OrderDetailService.class);
    protected TableService tableService = BeanFactory.getInstance("tableService",TableService.class);
    protected OrderService orderService = BeanFactory.getInstance("orderService", OrderService.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object  returnValue = null;
        //设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        // 获取操作类型;  【约定 > 俗成： 操作类型的值，必须对应servlet中的方法名称】
        String methodName = request.getParameter("method");
        try {
            //获取当前类运行的字节码
            Class clazz = this.getClass();
            //获取当前执行方法的method类型
            Method method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //执行方法
            returnValue = method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            returnValue = "/error/error.jsp";
        }
        //跳转
        WebUtils.goTo(request, response, returnValue);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
